<template>
  <div>
    <!-- 面包屑导航区 -->
    <bread-nav>
      <span slot="c1">权限管理</span>
      <span slot="c2">角色列表</span>
    </bread-nav>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="roleVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="['vcenters']"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRole(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色区 -->
    <el-dialog
      title="添加角色"
      :visible.sync="roleVisible"
      @close="addDialogClose"
      width="50%"
    >
      <el-form
        :model="addRoleForm"
        :rules="addFormRules"
        ref="roleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限区 -->
    <el-dialog title="分配权限" :visible.sync="setRightsVisible" width="50%">
      <!-- 树型控件 -->
      <el-tree
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultKey"
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户区 -->
    <el-dialog
      title="编辑"
      :visible.sync="editUserVisible"
      width="50%"
      @close="editClose"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="editRoleForm"
        :rules="addFormRules"
        ref="editRoleRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BreadNav from 'components/content/nav/BreadNav.vue'

export default {
  components: { BreadNav },
  name: 'Roles',
  data() {
    return {
      rolesList: [],
      // 添加角色框显示变量
      roleVisible: false,
      // 分配角色框显示变量
      setRightsVisible: false,
      // 添加角色数据
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 编辑角色数据
      editRoleForm: {},
      // 所有权限数据
      rightsList: [],
      // 树型控件区
      treeProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认选中的权限 key
      defaultKey: [],
      // 即将分配权限的角色id
      roleId: '',
      // 编辑用户框变量
      editUserVisible: false,
      // 编辑中存储角色信息
      editForm: {},
      // 要编辑角色的 id
      editId: '',
      // 添加角色和编辑角色共用规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '角色名称长度需在 2 到 8 个字符之间',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '角色描述长度需在 2 到 20 个字符之间',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
    },
    // 添加角色
    addRole() {
      this.$refs.roleFormRef.validate(async (valid) => {
        if (!valid) return

        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        console.log(res.meta.status)
        if (res.meta.status !== 201) {
          return this.$message.error('创建角色失败！')
        }
        this.getRolesList()
        this.roleVisible = false
        this.$message.success('创建角色成功！')
      })
    },
    addDialogClose() {
      this.$refs.roleFormRef.resetFields()
    },
    // 删除角色
    async deleteRole(id) {
      const deleteResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {
        this.$message.info('取消删除！')
      })

      if (deleteResult == 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('删除角色失败！')
        }
        this.getRolesList()
        this.$message.success('删除角色成功！')
      }
    },
    // 通过 id 删除权限
    async removeRightById(role, rightsId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => this.$message.info('取消删除'))

      if (confirmResult == 'confirm') {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightsId}`
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('删除权限失败！')
        }
        // 把更新后的值赋值给拷贝过来的 role ，这样就不用刷新整个页面使页面发生改变
        role.children = res.data
        this.$message.success('删除权限成功！')
      }
    },
    async getAllRights() {
      // 获取所有权限
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error('获取权限失败！')
      }
      this.rightsList = res.data
    },
    // 分配权限按钮
    setRights(role) {
      this.roleId = role.id
      this.defaultKey = []
      this.getAllRights()
      this.getLeftKeys(role, this.defaultKey)

      this.setRightsVisible = true
    },
    // 通过递归的方式获取角色下所有三级权限的 id、并保存到 defaukeys 数组中
    getLeftKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach((item) => {
        this.getLeftKeys(item, arr)
      })
    },
    // 点击为角色添加权限
    async allotRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]

      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightsVisible = false
    },
    // 通过 id 编辑角色按钮
    async editRole(id) {
      this.editId = id
      const { data: res } = await this.$http.get('roles/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！')
      }
      this.editRoleForm = res.data
      this.editUserVisible = true
    },
    // 编辑角色确认按钮
    editRoleInfo() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) return

        const { data: res } = await this.$http.put(
          'roles/' + this.editId,
          this.editRoleForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色信息失败!')
        }
        this.getRolesList()
        this.editUserVisible = false
        this.$message.success('修改角色信息成功！')
      })
    },
    // 关闭清空编辑框中数据
    editClose() {
      this.$refs.editRoleRef.resetFields()
    },
  },
}
</script>

<style scoped>
.el-tag {
  margin: 10px;
}
.bdtop {
  border: 1px solid #eee;
}
.bdbottom {
  border: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>